<?php
// +----------------------------------------------------------------------
// | APP版本
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------
namespace app\event\app;

use app\common\event\Base;
use app\event\ucenter\User as UserEvent;
use app\model\app\ExchangeCouponOrder as ExchangeCouponOrderModel;
use app\model\app\JdShare as JdShareModel;
use app\model\app\JdOrder as JdOrderModel;
use app\model\app\JdPrivilege as JdPrivilegeModel;
use app\model\app\JdGood as JdGoodModel;
use app\model\app\JdPid as JdPidModel;
use app\model\app\JdPidUser as JdPidUserModel;
use app\model\ucenter\User as UserModel;
use app\model\ucenter\UserMoneyLog as UserMoneyLogModel;
use app\model\ucenter\UserTask as UserTaskModel;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\helper\Str;

class Mt extends Base
{

    protected function setClient($client)
    {
        $client->setAppKey('675107a00b163');
        $client->setAppSecret('959b15cb9c214df2e8ebe9defa0aeb69');
        $client->setVersion('v3.0.0');
    }


    /**
     * 京东获取订单
     * @param $time
     * @param $old_time
     */
    public function mtLink($time = 1, $old_time = 1800)
    {
        try {

            require_once app()->getRootPath() . 'extend/dtk/DtkClient.php';
            require_once app()->getRootPath() . 'extend/dtk/VipSearchByKeywords.php';
            //订单详情
            $client = new \VipSearchByKeywords();
            $this->setClient($client);

            $param['keyword'] = '羽绒服';
            $param['chanTag'] = '羽绒服';
            $param['realCall'] = false;
            $param['openId'] = $time;
            $param['page'] = 1;

            $res = $client->setParams($param)->request();
            $result = json_decode($res, true);

           dump($result);
//            Db::startTrans();
//
//            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $result = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $result;

    }


    /**
     * 补单
     * @param $order
     * @param $user
     * @return array
     */
    public function supplement($order, $user)
    {
        try {
            if (!$order) {
                throw new Exception('订单异常');
            }
            $order['user_id'] = $user['id'];
            $order->save();

            $userTask = $this->_bindTask($order, $user);
            $this->_payFee($userTask, $order);
            $result['code'] = 0;
        } catch (\Exception $e) {
            // 回滚事务
            $result = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $result;
    }

    private function _bindTask($order, $user)
    {
        // 新增任务
        $userTask['task_id'] = 11;
        $userTask['relation_id'] = $order['id'];
        $userTask['task_type'] = 23;
        $userTask['user_id'] = $user['id'];
        $userTask['agent_id'] = $user['agent_id'];
        $userTask['title'] = $order['sku_name'];
        $userTask['logo'] = $order['goods_info']['imageUrl'];
        $userTask['money'] = $order['estimate_cos_price'];
        $userTask['commission'] = $order['estimate_fee'];
        $userTask['task_no'] = $order['order_id'];
//        $userTask['end_time'] = time() + 30 * 86400;
        $userTask['step'] = $order['valid_code'];
        $userTask['submit_info'] = $order->toArray();
        $userTask['status'] = 1;
        $userTask = UserTaskModel::create($userTask);
        if (!$userTask) {
            throw new Exception('系统故障');
        }
        return $userTask;
    }

    /**
     * 获取jingd订单
     * @param $time
     * @param $old_time
     */
    public function heightCommission($sort = 1)
    {

        require_once app()->getRootPath() . 'extend/dtk/DtkClient.php';
        require_once app()->getRootPath() . 'extend/dtk/GetTipList.php';
        require_once app()->getRootPath() . 'extend/dtk/GetTbParseContent.php';
        require_once app()->getRootPath() . 'extend/dtk/GetPrivilegeLink.php';
        require_once app()->getRootPath() . 'extend/dtk/GetListHeightCommission.php';
        //订单详情
        $client = new \GetListHeightCommission();

        $this->setClient($client);

        $param['pageSize'] = 100;
//        $param['cid'] = 1;
        $param['pageId'] = 1;
        $param['sort'] = $sort;
        $res = $client->setParams($param)->request();
        $data = json_decode($res, true);
        foreach ($data['data']['list'] as $index => $good) {
            $insert = [];
            foreach ($good as $index_g => $item) {
                $insert[Str::snake($index_g)] = $item;

            }
            if (JdGoodModel::where('id', $good['id'])->find()) {
                JdGoodModel::where('id', $good['id'])->update($insert);
            } else {
                JdGoodModel::create($insert);
            }
        }
        return json_decode($res, true);
    }

    protected function _payFee($userTask, $order)
    {
        $userTask['step'] = $order['valid_code'];

        //sku维度的有效码（-1：未知,2.无效-拆单,3.无效-取消,4.无效-京东帮帮主订单,
        //5.无效-账号异常,6.无效-赠品类目不返佣,7.无效-校园订单,8.无效-企业订单,9.无效-团购订单,
        //11.无效-乡村推广员下单,13.无效-违规订单,14.无效-来源与备案网址不符,15.待付款,
        //16.已付款,17.已完成（购买用户确认收货）,20.无效-此复购订单对应的首购订单无效,
        //21.无效-云店订单22.无效-PLUS会员佣金比例为0,23.无效-支付有礼,24.已付定金,25.
        // 违规订单-流量劫持,26. 违规订单-流量异常,27. 违规订单-违反京东平台规则,28.
        // 违规订单-多笔交易异常,29.无效-跨屏跨店,30.无效-累计件数超出类目上限,
        //29.无效-跨屏跨店,30.无效-累计件数超出类目上限,31.无效-黑名单sku

        if (in_array($userTask['step'], [-1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 13, 14, 20, 21, 22, 23, 25, 26, 27, 28, 29, 30, 31])) {
            // 订单失效。
            $userTask['status'] = 3;
        } elseif ($userTask['step'] == 15) {
            $userTask['status'] = 0;
        } elseif ($userTask['step'] == 16) {
            $userTask['status'] = 1;
        } elseif ($userTask['step'] == 17) {
            $userTask['status'] = 2;
            // 发放佣金
            $log = UserMoneyLogModel::where('user_id', $userTask['user_id'])->where('type', 39)
                ->where('order_id', $userTask['task_no'])
                ->where('channel', 'jd')->find();
            if (!$log) {
                $user = UserModel::where('id', $userTask['user_id'])->find();
                UserEvent::exhibitionIncome($user, $userTask['commission'], $userTask['title'], 39, $user['id'], $userTask['task_no'], 0, 'jd', 11);
            }
        } else {
            $userTask['status'] = 4;
        }

        $userTask->save();
        if ($userTask['status'] == 3 || $userTask['status'] == 4) {
            // 失败订单，查询是否扣款
            $log = UserMoneyLogModel::where('user_id', $userTask['user_id'])->where('type', 39)
                ->where('order_id', $userTask['task_no'])
                ->where('is_eversal', 0)
                ->where('channel', 'jd')->find();
            if ($log) {
                $user = UserModel::where('id', $userTask['user_id'])->find();
                UserEvent::exhibitionIncomeBack($user, 39, '电商返利因退款或退货返佣取消', $user['id'], $userTask['task_no'], 'jd', 11);
            }
        }
    }

    public function endPay($param)
    {
        try {
            $order = ExchangeCouponOrderModel::where('sn', $param['external_orderno'])->where('status', 1)->find();
            if (!$order) {
                throw new Exception('兑换不存在');
            }
            Db::startTrans();
            $order->allowField(['status', 'order_sn', 'msg', 'mobile', 'name', 'actual_price', 'pay_price', 'img', 'kami'])
                ->save($param);
            $task = UserTaskModel::where('task_type', 21)->where('relation_id', $order['id'])->find();
            if (!$task) {
                throw new Exception('任务不存在');
            }
            $task['step'] = $order['status'];
            if ($order['status'] == 4) {
                $task['status'] = 2;
            } elseif ($order['status'] == 3 || $order['status'] == 2) {
                $task['status'] = 1;
            } else {
                $task['reason'] = '接口异常' . $order['msg'];
                $task['status'] = 3;
            }
            $task->save();
            if ($task['status'] == 2) {
                $user = UserModel::where('id', $task['user_id'])->find();
                if ($user) {
                    UserEvent::exhibitionIncome($user, $task['commission'], $task['title'], 38, $user['id'], $task['task_no'], 0, $order['branch_id'], 13);
                }
            }
            Db::commit();
            $rep = ['code' => 0, 'message' => '接收成功'];
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $rep = ['code' => 1, 'message' => $e->getMessage()];
        }
        return $rep;
    }


}
